﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Transactions;
using static System.Formats.Asn1.AsnWriter;

namespace ZFY.UnitOfWork
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface)]
    public class UnitOfWorkAttribute : Attribute
    {
        public bool ThrowWhenExpection { get; set; } = true;
        /// <summary>
        /// Is this UOW transactional?
        /// Uses default value if not supplied.
        /// </summary>
        public TransactionScopeOption Scope { get;  set; }

        /// <summary>
        /// Timeout of UOW As milliseconds.
        /// Uses default value if not supplied.
        /// </summary>
        public int? Timeout { get; set; }

        /// <summary>
        /// If this UOW is transactional, this option indicated the isolation level of the transaction.
        /// Uses default value if not supplied.
        /// </summary>
        public System.Data.IsolationLevel? IsolationLevel { get; set; }

        /// <summary>
        /// Used to prevent starting a unit of work for the method.
        /// If there is already a started unit of work, this property is ignored.
        /// Default: false.
        /// </summary>
        public bool IsDisabled { get; set; }
        public UnitOfWorkAttribute()
        {
            Scope = TransactionScopeOption.Required;
        }
        public UnitOfWorkAttribute(TransactionScopeOption scope)
        {
            Scope = scope;
        }

        //TODO: More constructors!

        public virtual void SetOptions(UnitOfWorkOption options)
        {
            options.Scope = Scope;
            options.ThrowWhenExpection = ThrowWhenExpection;
            if (Timeout.HasValue)
            {
                options.Timeout = Timeout;
            }

            if (IsolationLevel.HasValue)
            {
                options.IsolationLevel = IsolationLevel;
            }
        }
    }
}
